package com.ruoyi.flowable.listener.move.moveRepair;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.equ.domain.EquMove;
import com.ruoyi.equ.service.IEquRepairService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 移动-维修-2监听
 */
@Slf4j
@Component("moveRepairListener_2")
public class MoveRepairListener_2 implements ExecutionListener {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final ISysDeptService deptService = SpringUtils.getBean(ISysDeptService.class);
    private static final ISysUserService userService = SpringUtils.getBean(ISysUserService.class);

    @Override
    public void notify(DelegateExecution execution) {
        try {
            //维修执行信息：派工部门+负责人
            String deptId = execution.getVariable("assignDept", String.class);
            String assignDept = deptService.selectDeptById(Long.valueOf(deptId)).getDeptName();
            String userId = execution.getVariable("leader", Integer.class).toString();
            String leader = userService.selectUserById(Long.valueOf(userId)).getNickName();
            String leaderPhone = execution.getVariable("leaderPhone", String.class);
            String assignDate = execution.getVariable("assignDate", String.class);
            String willTime = execution.getVariable("willTime", String.class);

            //移动-执行信息
            EquMove equMove = execution.getVariable("equMove", EquMove.class);
            Map<String, Object> executeInfoMap = objectMapper.readValue(equMove.getExecuteInfo(), new TypeReference<Map<String, Object>>() {});
            HashMap<String, Object> dataMap = new HashMap<>();
            dataMap.put("派工部门", assignDept);
            dataMap.put("维修负责人", leader);
            dataMap.put("联系电话", leaderPhone);
            dataMap.put("派工日期", assignDate);
            dataMap.put("预计完成时间", willTime);
            executeInfoMap.put("维修派工分配", dataMap);
            String executeInfo = objectMapper.writeValueAsString(executeInfoMap);

            equMove.setExecuteInfo(executeInfo);
            execution.setVariable("equMove", equMove);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
